package com.portal.portal.config.service;

import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletContext;

import com.portal.portal.config.DriverPageConfig;
import com.portal.portal.config.DriverRenderConfig;
import com.portal.portal.config.DriverResourceConfig;
import com.portal.portal.config.ResourceConfigReader;
import com.portal.util.constants.ServletAttributeKeys;
import com.portal.util.exception.PortalDriverConfigurationException;

public class DriverRenderServiceImpl implements DriverRenderService {

  private DriverRenderConfig driverRenderConfig = new DriverRenderConfig();

  public void destroy() throws PortalDriverConfigurationException {
  }

  public void init(ServletContext ctx) throws PortalDriverConfigurationException {

    if (ctx.getAttribute(ServletAttributeKeys.DRIVER_RENDER_CONFIG) != null) {
      driverRenderConfig = (DriverRenderConfig) ctx.getAttribute(ServletAttributeKeys.DRIVER_RENDER_CONFIG);
    } else {
      try {
        InputStream in = ctx.getResourceAsStream(ResourceConfigReader.DRIVER_CONFIG_FILE);
        DriverResourceConfig config = ResourceConfigReader.getFactory().parse(in);
        driverRenderConfig = config.getDriverRenderConfig();
      } catch (Exception e) {
        throw new PortalDriverConfigurationException(e);
      }
    }
  }

  public void addPage(DriverPageConfig driverPageConfig) {
    driverRenderConfig.addPage(driverPageConfig);
  }

  public DriverPageConfig getDefaultPage() {
    return driverRenderConfig.getDefaultPageConfig();
  }

  public DriverPageConfig getPage(String pageId) {
    return driverRenderConfig.getDriverPageConfig(pageId);
  }

  public List<DriverPageConfig> getPages() {
    return driverRenderConfig.getAllPages();
  }

  public void removePage(DriverPageConfig driverPageConfig) {
    driverRenderConfig.removePage(driverPageConfig);
  }

}
